#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/fcntl.h>
#include <unistd.h>
#include <string.h>
#include <math.h>

#define dimNum	5000*1000
#define factNum	dimNum 
#define RATE	0.01

int main(int argc, char ** argv){
	int *fact, *dim ;
	int i,j;
	int key,value;
	int *pos;
	int k=0;

	if(argc != 6){
		printf("binary_gen rate dimSize factSize dimColNum factColNum(at least 2)\n");
		exit(-1);
	}

	int rate = atoi(argv[1]);
	int dn = atoi(argv[2]);
	int fn = atoi(argv[3]);
	int dColNum = atoi(argv[4]);
	int fColNum = atoi(argv[5]);

	dim = (int *)malloc(sizeof(int) * dColNum);
	fact = (int *)malloc(sizeof(int) * fColNum);

	if(!dim || !fact){
		printf("failed to allocate memory!");
		exit(-1);
	}

	for(i=0;i<dColNum;i++){
		char buf[32]= {0};
		sprintf(buf, "dimTable%d",i);
		dim[i] = open(buf,O_WRONLY|O_CREAT);
	}

	for(i=0;i<fColNum;i++){
		char buf[32]= {0};
		sprintf(buf, "factTable%d",i);
		fact[i] = open(buf,O_WRONLY|O_CREAT);
	}

	for(i=0;i<dimNum*dn;i++){
		write(dim[0],&i,sizeof(int));
		for(j=1;j<dColNum;j++){
			srandom(i*i+1);
			value = random();
			write(dim[j],&value,sizeof(int));
		}
	}

	srandom(0);

	pos = (int *) malloc(sizeof(int) * factNum * fn);
	if(!pos){
		printf("failed to allocate memory\n");
		exit(-1);
	}
	memset(pos, 0, sizeof(int)* factNum);

	for(i=0;;i++){
		srandom(i*101 + 1);
		key = abs(random()) %(factNum * fn);
		if(pos[key] ==0 ){
			k++;
			pos[key] = 1;
			if(k == factNum * fn *RATE *rate)
				break;
		}
	}

	for(i=0;i<factNum *fn;i++){
		srandom(i*11+1);
		if(pos[i] == 1){
			key = abs(random()) % (dimNum * dn);
		}else
			key = random() % (dimNum *dn) + dimNum *dn;
		write(fact[0],&key,sizeof(int));
		value = random();
		for(j=1;j<fColNum;j++){
			write(fact[j],&value,sizeof(int));
		}
	}

	for(i=0;i<dColNum;i++){
		close(dim[i]);
	}
	for(i=0;i<fColNum;i++){
		close(fact[i]);
	}

	free(pos);
	return 0;
}
